#include "http_server.h"
#include "json.hpp"

HttpServer::HttpServer(){
}

HttpServer::~HttpServer(){
}

bool HttpServer::start(){

    server.Get("/",[](const httplib::Request& req, httplib::Response& res){
        res.set_content("Hello World", "text/plain");
    });

    server.Post("/",[&](const httplib::Request& req, httplib::Response& res){
        if(req.get_header_value("Content-Type")!="application/json"){
            res.status = 400;
            res.set_content("{\"error\":\"Invalid Content-Type\"}", "application/json");
            return false;
        }
        try
        {
            nlohmann::json requset_data = nlohmann::json::parse(req.body);
            
            for(auto& [k,v] : requset_data.items()){
                if("ip" == k){
                    std::string camera_ip = requset_data["ip"];
                    // std::cout << camera_ip << std::endl;
                }
                else{
                    hikCamera.setParams(k,v);
                }
            }
            hikCamera.setIp(camera_ip);
            // hikCamera.getInfo();
            hikCamera.start();
            if(hikCamera.setCFG()){
                res.set_content("set success", "text/plain");
            }
            else{
                res.set_content("set failed", "text/plain");
            }
        }
        catch(const std::exception& e)
        {
            std::cerr << e.what() << '\n';
        }
        
    });

    std::cout<<"server listening on port 18888\n";
    if(server.listen("0.0.0.0",18888)){
        std::cout<<"ok\n";
    }
    return true;
}